#!/usr/bin/env python3
"""
Docker镜像构建和推送脚本
用于构建login-reg:3.1镜像并推送到DockerHub
"""

import subprocess
import sys
import os
import platform

image_tag = "3.2" # 镜像的版本，每次上传前需要先在Docker Desktop中进行登录


def run_command(command, cwd=None):
    """
    运行shell命令并实时输出结果
    """
    print(f"执行命令: {command}")
    try:
        process = subprocess.Popen(
            command,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            cwd=cwd,
            text=True,
            bufsize=1,
            universal_newlines=True
        )

        # 实时输出命令执行结果
        while True:
            output = process.stdout.readline()
            if output == '' and process.poll() is not None:
                break
            if output:
                print(output.strip())

        rc = process.poll()
        if rc != 0:
            print(f"命令执行失败，返回码: {rc}")
            return False
        return True
    except Exception as e:
        print(f"执行命令时发生错误: {e}")
        return False


def build_and_push_docker_image():
    """
    构建并推送Docker镜像
    """
    # DockerHub用户名
    dockerhub_username = "yangke03"

    # 镜像名称和标签
    image_name = "login-reg"

    # 完整的镜像名称
    local_image = f"{image_name}:{image_tag}"
    remote_image = f"{dockerhub_username}/{image_name}:{image_tag}"

    print(f"开始构建和推送Docker镜像: {local_image}")
    print(f"DockerHub仓库: {remote_image}")

    # 1. 构建Docker镜像
    print("\n步骤1: 构建Docker镜像...")
    build_cmd = f"docker build -t {local_image} ."
    if not run_command(build_cmd):
        print("构建Docker镜像失败!")
        return False

    # 2. 标记镜像
    print("\n步骤2: 标记镜像...")
    tag_cmd = f"docker tag {local_image} {remote_image}"
    if not run_command(tag_cmd):
        print("标记镜像失败!")
        return False

    # 3. 推送镜像到DockerHub
    print("\n步骤3: 推送镜像到DockerHub...")
    push_cmd = f"docker push {remote_image}"
    if not run_command(push_cmd):
        print("推送镜像失败!")
        return False

    print("\n成功完成所有步骤!")
    print(f"镜像 {remote_image} 已成功推送到DockerHub")
    return True


def verify_image():
    """
    验证镜像是否成功构建
    """
    print("\n验证镜像...")
    # Windows系统使用findstr替代grep
    if platform.system() == "Windows":
        verify_cmd = "docker images | findstr login-reg"
    else:
        verify_cmd = "docker images | grep login-reg"
    run_command(verify_cmd)


def main():
    """
    主函数
    """
    print("Docker镜像构建和推送脚本")
    print("=" * 40)

    # 检查Docker是否可用
    print("检查Docker是否可用...")
    if not run_command("docker --version"):
        print("Docker未安装或不可用，请先安装Docker")
        return False

    # 构建和推送镜像
    success = build_and_push_docker_image()

    # 验证镜像
    if success:
        verify_image()

    return success


if __name__ == "__main__":
    try:
        success = main()
        if success:
            print("\n脚本执行成功!")
            sys.exit(0)
        else:
            print("\n脚本执行失败!")
            sys.exit(1)
    except KeyboardInterrupt:
        print("\n用户中断执行")
        sys.exit(1)
    except Exception as e:
        print(f"\n执行过程中发生错误: {e}")
        sys.exit(1)
